<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回
      </el-button>
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{ path: '/paymentManagement/application/applicationAll' }"
          >付款管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{ path: '/paymentManagement/application/applicationAll' }"
          >付款管理
        </el-breadcrumb-item>
        <el-breadcrumb-item
          :to="{ path: '/paymentManagement/application/applicationAll' }"
          >付款申请
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb"
            >{{ pageSatus[editStatus] }} {{ paymentNames }}</span
          >
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 非审批退回展示左侧主页面 -->
    <div class="ccui-app-container-detail" v-if="!approvalStatusLook">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="a">
            <!-- 新增、编辑详情 -->
            <PaymentRequestBasicInfo
              v-if="editStatus === 'add' || editStatus === 'edit'"
              class="commonClass"
              ref="basicInfo"
              @postPconcId="getPconcId"
              @clearTable="clearTable"
              :formData="formData"
              :isDisabled="isDisabled"
              @clear-table="clearTableData"
              @formCopyDataFun="formCopyDataFun"
            />

            <!-- 查看详情 -->
            <PaymentRequestLookDetail :formData="formData" v-else />
          </el-tab-pane>
          <el-tab-pane label="付款方式" name="fifth">
            <paymentType ref="paymentType" :detail="detailInfo" v-if="flag" />
          </el-tab-pane>
          <!-- 附件 -->
          <el-tab-pane label="附件" name="c">
            <Attachment
              ref="attachment"
              :isDisabled="isDisabled"
              :tableDataList="tableDataList"
              @attachmentSucessData="attachmentSucessData"
              class="commonClass"
            ></Attachment>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 审批退回展示界面 -->
    <ApprovalReturnDetails :id="approveId" v-if="approvalStatusLook && isTrue">
      <!--  审批状态图  -->
      <div class="detail-info-el-Label">
        <el-label :type="labelType[approvalStatus]"></el-label>
      </div>

      <el-tabs v-model="activeName" class="el-tabs__customize">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="a">
          <!-- 新增、编辑详情 -->
          <PaymentRequestBasicInfo
            v-if="editStatus === 'add' || editStatus === 'edit'"
            class="commonClass"
            ref="basicInfo"
            @postPconcId="getPconcId"
            @clearTable="clearTable"
            :formData="formData"
            :isDisabled="isDisabled"
            @clear-table="clearTableData"
            @formCopyDataFun="formCopyDataFun"
          />

          <!-- 查看详情 -->
          <PaymentRequestLookDetail :formData="formData" v-else />
        </el-tab-pane>
        <el-tab-pane label="付款方式" name="fifth">
          <paymentType ref="paymentType" :detail="detailInfo" v-if="flag" />
        </el-tab-pane>
        <!-- 附件 -->
        <el-tab-pane label="附件" name="c">
          <Attachment
            ref="attachment"
            :isDisabled="isDisabled"
            :tableDataList="tableDataList"
            @attachmentSucessData="attachmentSucessData"
            class="commonClass"
          ></Attachment>
        </el-tab-pane>
      </el-tabs>
    </ApprovalReturnDetails>
    <bottomGuide
      busiType="107"
      v-if="approvalStatusLook && approvalStatus == 4 && isTrue"
      approvalStatus="approvaled"
      exportMethod="get"
      methodGetPageType="exportPaymentDetail"
      :curPageId="JSON.parse(this.$route.params.id).id"
      :businessCode="businessCode"
      @handleBack="handleBack"
    />

    <!--  底部操作按钮  -->
    <el-bottom-guide v-else>
      <ul class="ccui-bottom-button">
        <li v-show="!isDisabled">
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandleKeep"
            >暂存
          </el-button>
        </li>
        <li v-show="!isDisabled">
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitSaveCheck"
            >保存并校验
          </el-button>
        </li>
        <li v-show="!isDisabled">
          <el-button type="bottom" icon="icon-ccui-save" @click="submitHandle"
            >保存并提交
          </el-button>
        </li>
        <div v-show="!isDisabled" class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回
          </el-button>
        </li>
        <!-- <li v-if="['4'].includes(settlementForm.settlementStatus)">
          <el-button type="bottom" icon="icon-ccui-export" @click="handlExport"
          >导出
          </el-button>
        </li> -->
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import PaymentRequestBasicInfo from "@/app/paymentManagement/paymentApplication/components/paymentRequestBasicInfo";
import Attachment from "@/app/paymentManagement/components/attachment";
import ApprovalReturnDetails from "./components/approvalReturnDetails.vue";

import paymentType from "@/app/paymentManagement/paymentApplication/components/paymentType";
import paymentDetail from "@/app/paymentManagement/mixins/paymentDetail";
import PaymentRequestLookDetail from "./components/paymentRequestLookDetail.vue";
import bus from "./js/bus";
import {
  insertPayment,
  updatePayment
} from "@/app/paymentManagement/paymentApplication/apis";
import { qryPaymentdetail } from "./apis";
import publicComponent from "@/basa/components/public";

export default {
  name: "applicationDetail",
  mixins: [paymentDetail],
  components: {
    PaymentRequestBasicInfo,
    Attachment,
    PaymentRequestLookDetail,
    ApprovalReturnDetails,
    paymentType,
    bottomGuide: publicComponent.bottomGuide
  },
  data() {
    return {
      isTrue: false,
      businessCode: "",
      downloadUrl: this.$addUrlPerFix(process.env.VUE_APP_BASE_URL),
      // 可读可写控制
      isDisabled: false,
      // 编辑状态
      editStatus: "add",
      activeName: "a",
      concId: null,
      clearTableList: null,
      //表单数据
      formData: "",
      detailInfo: {},
      flag: false,
      payTypeListBOS: []
    };
  },
  mounted() {
    var _this = this;
    bus.$on("userEvent", function (data) {
      _this.payTypeListBOS = [];
      _this.flag = false;
      _this.detailInfo = Object.assign(data, {
        state: "detail"
      });
      _this.payTypeListBOS = data.payTypeListBOS.map((n, i) => ({
        smpPayTypeBO: {
          ...n.smpPayTypeBO,
          sn: i,
          id: this.state === "create" ? null : n.smpPayTypeBO.id
        },
        smpPayTypeItemBOS: n.smpPayTypeItemBOS.map((m, i) => ({
          ...m,
          endDate: null,
          sn: i,
          id: this.state === "create" ? null : m.id
        }))
      }));
      console.log(_this.payTypeListBOS);
      _this.flag = true;
    });
  },
  activated() {
    this.flag = false;
  },
  beforeRouteLeave(to, from, next) {
    this.isTrue = false;
    next();
  },
  methods: {
    // 付款申请新增入参过滤
    parameterFilters(optId) {
      this.formCopyData.optId = optId;
      this.formCopyData.fileList = Array.from(new Set(this.attachmentUploadId));
      const parameter = {
        optId: "",
        id: "",
        paymentCode: "",
        paymentName: "",
        contractId: "",
        contractCode: "",
        contractName: "",
        initTotalContractPriceIncludeTax: "",
        chExchangeRate: "",
        settledPrice: "",
        invoiceIncludeTax: "",
        paymentPrice: "",
        payablePrice: "",
        paymentMode: "",
        reportInOrgCode: "",
        reportInOrgName: "",
        payee: "",
        paymentMoney: "",
        paymentTime: "",
        currencyCode: "",
        currencyName: "",
        reportUsername: "",
        reportOpenid: "",
        reportTime: "",
        approvalStatus: "",
        approvalTime: "",
        changeStatus: "",
        paymentType: "",
        billMonths: "",
        reasons: "",
        remark: "",
        isDelete: "",
        fileList: [],
        partyBExtOid: "",
        partyBId: "",
        companyOrgId: ""
      };
      console.log("入参过滤前formCopyData", this.formCopyData);
      for (const key in parameter) {
        parameter[key] = this.formCopyData[key];
      }
      console.log("入参过滤后parameter", parameter);
      return parameter;
    },
    // 校验
    formVerification(type, optId) {
      let refsDom = this.$refs["basicInfo"].$refs["basicInfo"];
      // 暂存不走校验 保存 提交的走校验
      if (optId !== 1) {
        refsDom.validate(valid => {
          if (valid) {
            if (type === "edit") this.updatePaymentSubmit(optId);
            else this.insertPaymentSubmit(optId);
          } else {
            this.$showErrorMessage("付款申请单基本信息不完整，请编辑后保存");
          }
        });
      } else {
        if (type === "edit") this.updatePaymentSubmit(optId);
        else this.insertPaymentSubmit(optId);
      }
    },
    // 付款申请编辑页-暂存、保存并校验、保存并提交
    updatePaymentSubmit(optId) {
      // 不能是0
      const isZero = ["0", "0.0", "0.00", "0."];
      if (isZero.includes(this.formCopyData.paymentMoney)) {
        this.$showErrorMessage("付款申请单基本信息不完整，请编辑后保存");
        return;
      }
      const obj = this.parameterFilters(optId);
      updatePayment({
        ...obj,
        payTypeListBOS: this.payTypeListBOS,
        isShowPageLoading: true
      }).then(res => {
        // 成功提示框
        this.tipsMessage(optId, res);

        // 返回上一页
        this.$router.go(-1);
      });
    },
    // 付款申请新增页-暂存、保存并校验、保存并提交
    insertPaymentSubmit(optId) {
      // 不能是0
      const isZero = ["0", "0.0", "0.00", "0."];
      if (isZero.includes(this.formCopyData.paymentMoney)) {
        this.$showErrorMessage("付款申请单基本信息不完整，请编辑后保存");
        return;
      }

      const obj = this.parameterFilters(optId);

      insertPayment({
        ...obj,
        payTypeListBOS: this.payTypeListBOS,
        isShowPageLoading: true
      }).then(res => {
        // 成功提示框
        this.tipsMessage(optId, res);

        // 返回上一页
        this.$router.go(-1);
      });
    },
    // 付款申请编辑详情编辑查询
    getLookDetailData(id) {
      this.payTypeListBOS = [];
      qryPaymentdetail({ id }).then(res => {
        this.formData = res.data.data;
        this.businessCode = res.data.data.paymentCode;
        this.detailInfo = Object.assign(res.data.data, {
          state: "detail"
        });
        this.payTypeListBOS = this.formData.payTypeListBOS.map((n, i) => ({
          smpPayTypeBO: {
            ...n.smpPayTypeBO,
            sn: i,
            id: this.state === "create" ? null : n.smpPayTypeBO.id
          },
          smpPayTypeItemBOS: n.smpPayTypeItemBOS.map((m, i) => ({
            ...m,
            sn: i,
            endDate: null,
            id: this.state === "create" ? null : m.id
          }))
        }));
        this.flag = true;
        this.formData.initTotalContractPriceIncludeTax =
          Number(res.data.data.initTotalContractPriceIncludeTax).toFixed(2) ||
          "0.00";
        this.formData.settledPrice =
          Number(res.data.data.settledPrice).toFixed(2) || "0.00";
        this.formData.invoiceIncludeTax =
          Number(res.data.data.invoiceIncludeTax).toFixed(2) || "0.00";
        this.formData.paymentPrice =
          Number(res.data.data.paymentPrice).toFixed(2) || "0.00";
        this.formData.payablePrice =
          Number(res.data.data.payablePrice).toFixed(2) || "0.00";
        // 处理时间格式
        this.dateFormatFun(this.formData);
        this.tableDataList = res.data.data.fileList || [];

        // 审批记录状态
        this.approvalStatus = res.data.data.approvalStatus;

        // 清单名称展示
        this.paymentNames = res.data.data.paymentName;

        this.isTrue = true;
      });
    },
    // 提示框
    tipsMessage(optId, res) {
      let message = "";
      if (optId === 1) message = `暂存成功`;
      if (optId === 2) message = `保存并校验成功`;
      if (optId === 3) message = `保存并提交成功`;

      // 提示
      this.$message({
        message,
        type: res.data.code === "0" ? "success" : "error",
        showClose: true,
        ccuiCustom: true
      });
    },
    // 导出
    handlExport() {
      window.open(
        this.downloadUrl +
          `/apis/smp/export/exportPaymentDetail?priId=${
            JSON.parse(this.$route.params.id).id
          }`
      );
    },
    handleBack() {
      this.$router.go(-1);
      //  this.$router.push(`/paymentManagement/application/applicationAll`);
    }
  }
};
</script>

<style scoped lang="scss">
.commonClass {
  margin-top: 5px;
}

/deep/ .el-group-title .group-content {
  margin-top: 40px;
}
/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
  position: absolute;
  top: 0px;
  right: 0;
}
</style>
